import json
import os
from django.core.management.base import BaseCommand
from ...models import ShippingFeeConfig


class Command(BaseCommand):
    help = '从config.json文件导入运费配置到数据库'

    def handle(self, *args, **options):
        try:
            # 获取config.json文件路径
            current_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
            config_path = os.path.join(current_dir, 'config.json')
            
            if not os.path.exists(config_path):
                self.stdout.write(
                    self.style.ERROR(f'配置文件不存在: {config_path}')
                )
                return
            
            # 读取配置文件
            with open(config_path, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
            
            # 清空现有数据
            ShippingFeeConfig.objects.all().delete()
            self.stdout.write('已清空现有运费配置数据')
            
            # 导入黑猫运费配置
            yamato_prices = config_data.get('yamato_prices', [])
            for item in yamato_prices:
                volume = item.get('volume')
                prices = item.get('prices', {})
                
                for region, price in prices.items():
                    ShippingFeeConfig.objects.create(
                        carrier='YAMATO',
                        volume=volume,
                        region=region,
                        price=price,
                        is_active=True
                    )
            
            self.stdout.write(f'已导入 {len(yamato_prices)} 条黑猫运费配置')
            
            # 导入佐川运费配置
            sagawa_prices = config_data.get('sagawa_prices', [])
            for item in sagawa_prices:
                volume = item.get('volume')
                prices = item.get('prices', {})
                
                for region, price in prices.items():
                    ShippingFeeConfig.objects.create(
                        carrier='SAGAWA',
                        volume=volume,
                        region=region,
                        price=price,
                        is_active=True
                    )
            
            self.stdout.write(f'已导入 {len(sagawa_prices)} 条佐川运费配置')
            
            total_count = ShippingFeeConfig.objects.count()
            self.stdout.write(
                self.style.SUCCESS(f'运费配置导入完成，共导入 {total_count} 条记录')
            )
            
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'导入失败: {str(e)}')
            ) 